<template>
    <div class="map-wrapper">
        <div id="panel"></div>
        <div style="position: absolute;top: 20px;height: 60px;left: 100px;width: 400px;z-index: 999">
            <el-input v-model="searchText" placeholder="请输入搜索关键字" id="searchInputId" />

            <el-input v-model="startName" style="margin-right: 10px" placeholder="起始地点"></el-input>
            <el-input id="end" v-model="endName" style="margin-right: 10px" placeholder="目的地点"></el-input>
            <el-select v-model="rule">
                <el-option v-for="item in routeRules" :key="item.value" :label="item.label" :value="item.value"
                    placeholder="请选择驾车算路策略" />
            </el-select>
            <el-button @click="goView" style="margin-left: 10px">搜索</el-button>
        </div>
        <div class="route-list"
            v-if="routeArr.length > 0">
            路线规划策略： {{ policy }}
            <el-row v-for="(item, index) in routeArr" :key="index">
                {{ item.instruction }}
            </el-row>
        </div>
        <div id="amap"></div>

        <div class="draw-area">
            <div class="select">
                <div style="margin: 10px 0">
                    <el-button @click="drawOther(mouseTool)">绘制多边形</el-button>
                    <el-button @click="drawRect(mouseTool)">绘制矩形</el-button>
                    <el-button @click="drawCircle(mouseTool)">绘制圆形</el-button>
                    <el-button @click="stopDrawAndClear(mouseTool)">清除</el-button>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { onMounted, onUnmounted, ref } from "vue";
import AMapLoader from "@amap/amap-jsapi-loader";
import { addLayers } from "../utils/addLayers";
import { poiSearch } from "../utils/poiSearch";
import { showInfo } from "../utils/showInfo";
import { createMarker } from "../utils/marker";
import { drawOther, drawRect, drawCircle, stopDrawAndClear } from "../utils/draw";
import { plugins, routeRules } from "../constant/common";
import {distProvince} from "../utils/distProvince";

let map: any = null
let placeSearch,
    AMapObj: any,
    geocoder: { getAddress: (arg0: any, arg1: (status: any, result: any) => void) => void; }
let mouseTool: any = null
let circleId = 1
let auto = ref('')
let autoOptions = {
    input: 'searchInputId', // 这个字符串要和搜索框的id保持一致
}
let searchText = ref('')


let startName = ref('')
let endName = ref('')
let rule = ref('')
let routeArr = ref([])
let policy = ref('')

onMounted(() => {
    initMap();
});

async function initMap() {
    await AMapLoader.load({
        key: 'ef851cb218a268aafe22bcc739052be0',
        version: '2.0',
        plugins: plugins,
    }).then(AMap => {
        AMapObj = AMap
        map = new AMap.Map('amap', {
            zoom: 12,
            resizeEnable: true,
            /**
             * 创建AMap.Map对象时如果没有传入center参数
             * 地图也会自动定位到您所在城市并显示，这就是JS API的初始加载定位：无需传入对应参数就能获取大致的定位信息
             * 但是当写了center参数，那么地图也会显示到您传入的center参数对应的位置
             */
            // center: [103.841856, 36.053549],
            viewMode: "3D",
        })
        // 图层切换
        const mapType = new AMap.MapType()
        // 鹰眼
        const hawkEye = new AMap.HawkEye({
            position: 'RB'
        })
        // 缩放条
        const toolbar = new AMap.ToolBar({
            position: 'LT'
        })
        // 比例尺
        const scale = new AMap.Scale()
        // 定位
        const geolocation = new AMap.Geolocation({
            enableHighAccuracy: true,//是否使用高精度定位，默认:true
            timeout: 10000,          //超过10秒后停止定位，默认：无穷大
            maximumAge: 0,           //定位结果缓存0毫秒，默认：0
            convert: true,           //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
            showButton: true,        //显示定位按钮，默认：true
            buttonPosition: 'LB',    //定位按钮停靠位置，默认：'LB'，左下角
            buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
            showMarker: true,        //定位成功后在定位到的位置显示点标记，默认：true
            showCircle: true,        //定位成功后用圆圈表示定位精度范围，默认：true
            panToLocation: true,     //定位成功后将定位到的位置作为地图中心点，默认：true
            zoomToAccuracy: true      //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
        });
        geocoder = new AMap.Geocoder({
            city: '全国',
        });
        map.addControl(geolocation)  // 定位组件
        map.addControl(toolbar)  // 放大缩小组件
        map.addControl(scale)  // 比例尺
        map.addControl(hawkEye)  // 鹰眼
        map.addControl(mapType)  // 图层切换

        /**
         * 添加图层： 官方卫星、路网图层
         * 上面如果添加了组件：map.addControl(mapType)
         * 这里就没必要手动添加图层了
        */
        // addLayers(map, AMap)

        // POI搜索
        poiSearch(auto.value, autoOptions, map, AMap)
        // 地图事件绑定
        bindEvent(AMap)

        // 覆盖物
        mouseTool = new AMap.MouseTool(map); //创建鼠标工具插件实例
        // 区域高亮
        distProvince(map, AMap)
    }
    );
}

// 鼠标双击事件
const doubleClick = (e: any, AMap: any) => {
    console.log('您在 [ ' + e.lnglat.getLng() + ',' + e.lnglat.getLat() + ' ] 的位置双击了地图！')
    const x = e.lnglat.getLng()
    const y = e.lnglat.getLat()
    // 信息窗体
    showInfo(geocoder, map, AMap, e, x, y)
}

// 鼠标移动事件
const showInfoMove = () => {
    console.log('您移动了您的鼠标！')
}

// 鼠标点击事件
const signClick = (e: any, AMap: any) => {
    console.log('您在 [ ' + e.lnglat.getLng() + ',' + e.lnglat.getLat() + ' ] 的位置单击了地图！')
    const x = e.lnglat.getLng()
    const y = e.lnglat.getLat()
    // 信息窗体
    //showInfo(geocoder, map, AMap, e, x, y)
    createMarker(map, AMap, x, y)
}

// 地图事件绑定
const bindEvent = (AMap: any) => {
    console.log("事件绑定成功")
    map.on('click', (e: any) => signClick(e, AMap));
    //map.on('dblclick', (e: any) => doubleClick(e, AMap));
    //map.on('mousemove', showInfoMove);
}

// 路径规划
const goView = () => {
  // eslint-disable-next-line no-undef
  const driving = new AMapObj.Driving({
    map,
    // 驾车路线规划策略，AMap.DrivingPolicy.LEAST_TIME是最快捷模式
    // eslint-disable-next-line no-undef
    // policy: AMapObj.DrivingPolicy.LEAST_TIME  // 路线最快
    policy: rule.value  // 路线最快
  })
  const points = [
    { keyword: startName.value, city: '广州' },
    { keyword: endName.value, city: '广州' }
  ]

  driving.search(points, (status: any, result: any) => {
    // 未出错时，result即是对应的路线规划方案
    console.log('status=', status)
    console.log('result=', result)
    if (status === 'complete') {
      routeArr.value = result.routes[0].steps
      policy.value = result.routes[0].policy
      console.log(routeArr.value)
    }
  })
}

onUnmounted(() => {
    map?.destroy();
});
</script>

<style lang="less" scoped>
.map-wrapper {
    #amap {
        width: 100vw;
        height: 100vh;
    }
}

::v-deep .amap-sug-result {
    color: #2c2c2c !important;
}

#panel {
    position: absolute;
    top: 20px;
    right: 20px;
    z-index: 999;
}

.draw-area {
    position: absolute;
    bottom: 10px;
    right: 200px;
    display: flex;
    justify-content: center;

    .select {
        background-color: white;
        color: #2c2c2c;
        padding: 0 10px;
        margin-right: 10px;
        border: 1px solid #ccc;
        border-radius: 5px;
    }

    .action {
        display: flex;
        align-items: center;
    }
}

.route-list {
    height: 400px; 
    width: 600px; 
    position: absolute; 
    top: 100px; 
    z-index: 9999; 
    border: 1px springgreen solid;
    overflow: scroll;
    background: white;
    padding: 10px;
}
</style>